#include "aiderterm.h"

AiderTerm::AiderTerm(QWidget *parent) : QWidget(parent) {
    // 创建布局
    layout = new QVBoxLayout(this);

    setWindowTitle("Aider Terminal");

    // 创建 QTermWidget
    term = new QTermWidget(0, this);
    term->setShellProgram("/bin/sh");

    // 设置字体
    QFont font = term->getTerminalFont();
    font.setPointSize(12);
    term->setTerminalFont(font);
    term->setScrollBarPosition(QTermWidget::ScrollBarRight);
    term->setColorScheme("SolarizedLight");

    term->startShellProgram();

    // 添加到布局
    layout->addWidget(term);

    setLayout(layout);

    connect(term, &QTermWidget::finished, this, &AiderTerm::close);
}

void AiderTerm::setPythonBinPath(QString path) {
    pythonBinPath = path;
}

void AiderTerm::setEnv(QString key, QString val) {
    QStringList env = QProcess::systemEnvironment();
    env.append(key + "=" + val);
    term->setEnvironment(env);
}

void AiderTerm::cd(QString path) {
    QString templateCmd = "cd %1\n";
    term->sendText(templateCmd.arg(path));
}

void AiderTerm::execute(QString apiType, QString apiKey, QString fileName) {
    if (apiType.isEmpty() || apiKey.isEmpty())
        return;
    QString templateCmd = "env %1=%2 %3 -m aider --deepseek %4\n";
    QString cmd = templateCmd.arg(apiType).arg(apiKey).arg(pythonBinPath).arg(fileName);
    term->sendText(cmd);
}

AiderTerm::~AiderTerm() {
    delete term;
    delete layout;
}
